package cn.jiahua.test4;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  A 和  B 操作同一个变量   num=0;
 * A是生产者   num+1
 * B是消费者   num-1
 * Synchronzied 实现
 */
public class Test {

    public static void main(String[] args) {
        Data data=new Data();

        new Thread(()->{
            for (int i=0;i<10;i++){
                data.increment();
            }
        },"A").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                data.decrement();
            }
        },"B").start();


        new Thread(()->{
            for (int i=0;i<10;i++){
                data.increment();
            }
        },"C").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                data.decrement();
            }
        },"D").start();

    }

}

class Data{
    private int number=0;
    Lock lock =new ReentrantLock();
    Condition NotFull =lock.newCondition();  //没满
    Condition NotEntity=lock.newCondition(); //没空


    public void increment(){
        lock.lock();
        try {
            while (number != 0) {
                NotFull.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "===》生产者放入数据了" + number);
            NotEntity.signal();
        }catch (Exception e){
            lock.unlock();
        }
    }

    public void decrement(){
        lock.lock();
        try {
            while (number == 0) {
                try {
                    NotEntity.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "===》消费者消费数据" + number);

            NotFull.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }






}
